// pages/cabinet/cabinet.js
const userModel = require('../../model/user');
const cabinetService = require('../../services/cabinet/cabinet');
const {generateAndUpdateQrcode} = require('../../services/cabinet/cabinet');
const { staticUrl } = require('../../utils/config');
const globalModel = require('../../model/global');

Page({ 
  data: {
    role: '', // 用户角色
    userId: null,
    cabinetApplication: null,
    cabinetStatus: '',
    translatedStatus: '',
    showNewLayout: false,
    isDelivered: false,
    wineInfo: [],
    qrcodeUrl: '',
    applicationId: null,
    activeTab: 'member',
  },

  onShareAppMessage() {
    return {
      title: "美酒城市",
      path: "/pages/cabinet/cabinet",
    }
  },
  
  onShow() {
    const userData = userModel.getUserData();
    const role = userData.info.role;
    const userId = userData.info.id;

    this.setData({
      role,
      userId,
    });

    if (role === 'GUEST' || role === 'MEMBER' || role === 'CABINET_OWNER') {
      this.fetchCabinetData(userId);
    }

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
            active: 2
        })
    }

    if(role === 'GUEST') { this.setData({ activeTab: 'member' }) }
    else { this.setData({ activeTab: 'owner' }) }
  },
  onTabClick(e) {
    const { tab } = e.currentTarget.dataset;
    this.setData({
      activeTab: tab
    });
  },
 
  fetchCabinetData() {
    cabinetService.getCabinetApplicationByUser()
      .then(data => {
        const status = data.status; 
        const newLayoutStatuses = [
          'PAYED', 
          'PENDING',
          'APPROVED',
          'SHIPPED',
          'DELIVERED',
          'FAIL',
          'RETURN_PENDING',
          'RETURNED'
        ];
        const showNewLayout = newLayoutStatuses.includes(status);
        const translatedStatus = this.translateStatus(status);
        const isDelivered = (status === 'DELIVERED');

        let wineInfo = []; 
        if (isDelivered && data.cabinetBundle && data.cabinetBundle.wines) {
          wineInfo = data.cabinetBundle.wines.map(winebumdle => {
            return `${winebumdle.wine.product.name} ${winebumdle.wine.aroma} ${winebumdle.wine.alcoholContent}度 - ${winebumdle.quote}瓶`});
        }

        this.setData({
          cabinetApplication: data,
          cabinetStatus: status,
          translatedStatus: translatedStatus,
          showNewLayout,
          isDelivered,
          wineInfo,
          applicationId: data.id,
        }, () => {
          // 在状态不是REJECTED, FAIL, RETURNED时处理二维码
          if (!['REJECTED', 'FAIL', 'RETURNED'].includes(status)) {
            this.handleQrcode(data); // 调用新的处理二维码函数
          }
        });
      })
      .catch((err) => {
        console.error("fetchCabinetData error:", err); // 打印错误信息
        this.setData({
          cabinetApplication: null,
          cabinetStatus: '',
          translatedStatus: '',
          showNewLayout: false,
          isDelivered: false,
          wineInfo: [],
          qrcodeUrl: '',
          applicationId: null
        });
      });
  },
 
  async handleQrcode(applicationData) {
    const { id: applicationId } = applicationData;
    const userData = userModel.getUserData();
    const qrCodeUrl = userData?.info.cabinetOwnerApplication?.qrCodeUrl; 

    if (qrCodeUrl) {
      // 本地存在二维码，直接使用
      this.setData({ 
        qrcodeUrl: `${staticUrl}${qrCodeUrl}`
      });
    } else if (applicationId) {
      // 本地不存在，调用云函数生成
      this.generateQrcode(this.data.userId, applicationId);
    } else {
      console.warn("Application ID is missing, cannot generate QR code.");
    }
  },

  navigateToReplenish() {
    wx.switchTab({ url: '/pages/goods/list/index' });
  },

  translateStatus(status) {
    switch (status) {
      case 'PAYED':
        return '待支付押金';
      case 'PENDING':
        return '审核中';
      case 'APPROVED':
        return '审核通过，待发货';
      case 'REJECTED':
        return '申请被拒绝';
      case 'SHIPPED':
        return '已发货';
      case 'DELIVERED':
        return '已到货';
      case 'FAIL':
        return '申请错误';
      case 'RETURN_PENDING':
        return '已申请召回';
      case 'RETURNED':
        return '已召回';
      default:
        return '';
    }
  },


  confirmReceipt() {
    // 获取当前申请的ID
    const applicationId = this.data.cabinetApplication?.id;
    if (!applicationId) {
      wx.showToast({
        title: '申请ID缺失',
        icon: 'none'
      });
      return;
    }

    this.setData({
      showConfirmPopup: true,  
      applicationId: applicationId
    });
  },
  // 当弹窗组件点击「确定」上传凭证，并完成后端更新后，回调父页面执行此方法
  onConfirmReceiptSuccess() {
    // 弹窗完成更新后，刷新页面数据
    this.fetchCabinetData(this.data.userId);
    this.setData({ showConfirmPopup: false });
  },
  onCloseConfirmPopup() {
    this.setData({ showConfirmPopup: false });
  },

  applyRecall() {
    const applicationId = this.data.cabinetApplication.id;
    const servicePhone = globalModel.getServicePhone() || '138xxxx';

    wx.showModal({
      title: '召回确认',
      content: `您是否需要申请召回该酒柜？\n
      请备齐以下材料，并与您的区域代理联系，或联系${servicePhone}。\n
      1. XXXXXXX；\n
      2. XXXXXXX；\n
      3. XXXXXXX；`,
      success(res) {
        if (res.confirm) {
            cabinetService.applyRecall(applicationId)
            .then(res => {
              wx.showToast({
                title: res.message || '召回已申请',
                icon: 'none'
              });
              this.fetchCabinetData(this.data.userId);
              // 根据后端返回更新状态
              const newStatus = res.application.status;
              const translatedStatus = this.translateStatus(newStatus);
              this.setData({
                cabinetStatus: newStatus,
                translatedStatus: translatedStatus
              });
            })
            .catch(() => {
              wx.showToast({
                title: '召回申请失败，请稍后重试',
                icon: 'none'
              });
            });
        }
      },
      fail() {
        
      }
    });

  },

  generateQrcode(userId, applicationId) {
    generateAndUpdateQrcode(userId, applicationId)
      .then(({fileUrl, base64}) => {
        
        // 更新当前页面的 qrcodeUrl，用于显示
        this.setData({ 
          qrcodeUrl: `${staticUrl}${fileUrl}`
        });
      })
      .catch(error => {
        
      });
  }
  
});